import { get, post, put, del } from '@/utils/request'
import { API_ENDPOINTS, replaceUrlParams } from '@/config/api'

/**
 * 优惠券管理API
 */

// 获取优惠券列表
export function getCouponsList(params = {}) {
  return get(API_ENDPOINTS.COUPONS.LIST, {
    page: params.page || 0,
    size: params.size || 20,
    name: params.name || '',
    type: params.type || '',
    status: params.status || '',
    startDate: params.startDate || '',
    endDate: params.endDate || '',
    sortBy: params.sortBy || 'createTime',
    sortOrder: params.sortOrder || 'desc'
  })
}

// 获取优惠券详情
export function getCouponDetail(couponId) {
  const url = replaceUrlParams(API_ENDPOINTS.COUPONS.UPDATE, { id: couponId })
  return get(url)
}

// 创建优惠券
export function createCoupon(couponData) {
  return post(API_ENDPOINTS.COUPONS.CREATE, {
    name: couponData.name,
    type: couponData.type,
    value: couponData.value,
    minAmount: couponData.minAmount,
    total: couponData.total,
    useLimit: couponData.useLimit,
    startTime: couponData.dateRange?.[0],
    endTime: couponData.dateRange?.[1],
    validDays: couponData.validDays,
    useTime: couponData.useTime,
    useScope: couponData.useScope,
    scopeIds: couponData.scopeIds || [],
    userLevel: couponData.userLevel,
    levelIds: couponData.levelIds || [],
    description: couponData.description || ''
  })
}

// 更新优惠券
export function updateCoupon(couponId, couponData) {
  const url = replaceUrlParams(API_ENDPOINTS.COUPONS.UPDATE, { id: couponId })
  return put(url, {
    name: couponData.name,
    type: couponData.type,
    value: couponData.value,
    minAmount: couponData.minAmount,
    total: couponData.total,
    useLimit: couponData.useLimit,
    startTime: couponData.dateRange?.[0],
    endTime: couponData.dateRange?.[1],
    validDays: couponData.validDays,
    useTime: couponData.useTime,
    useScope: couponData.useScope,
    scopeIds: couponData.scopeIds || [],
    userLevel: couponData.userLevel,
    levelIds: couponData.levelIds || [],
    description: couponData.description || ''
  })
}

// 删除优惠券
export function deleteCoupon(couponId) {
  const url = replaceUrlParams(API_ENDPOINTS.COUPONS.DELETE, { id: couponId })
  return del(url)
}

// 批量删除优惠券
export function deleteCoupons(couponIds) {
  return post(API_ENDPOINTS.COUPONS.DELETE.replace('/{id}', '/batch'), {
    couponIds: couponIds
  })
}

// 激活优惠券
export function activateCoupon(couponId) {
  const url = replaceUrlParams(API_ENDPOINTS.COUPONS.ACTIVATE, { id: couponId })
  return post(url)
}

// 停用优惠券
export function deactivateCoupon(couponId) {
  const url = replaceUrlParams(API_ENDPOINTS.COUPONS.DEACTIVATE, { id: couponId })
  return post(url)
}

// 批量激活优惠券
export function activateCoupons(couponIds) {
  return post(API_ENDPOINTS.COUPONS.ACTIVATE.replace('/{id}', '/batch'), {
    couponIds: couponIds
  })
}

// 批量停用优惠券
export function deactivateCoupons(couponIds) {
  return post(API_ENDPOINTS.COUPONS.DEACTIVATE.replace('/{id}', '/batch'), {
    couponIds: couponIds
  })
}

// 获取优惠券统计
export function getCouponStatistics() {
  return get(API_ENDPOINTS.COUPONS.STATISTICS)
}

// 导出优惠券数据
export function exportCoupons(params = {}) {
  return get(API_ENDPOINTS.COUPONS.LIST + '/export', params, {
    responseType: 'blob'
  })
}

// 优惠券类型枚举
export const COUPON_TYPES = {
  THRESHOLD: 'threshold',      // 满减券
  DISCOUNT: 'discount',        // 折扣券
  INSTANT: 'instant',          // 立减券
  NEWUSER: 'newuser',          // 新人券
  REGULAR: 'regular',          // 普通优惠券
  STACKABLE: 'stackable'       // 叠加券
}

// 优惠券类型文本映射
export const COUPON_TYPE_TEXT = {
  [COUPON_TYPES.THRESHOLD]: '满减券',
  [COUPON_TYPES.DISCOUNT]: '折扣券',
  [COUPON_TYPES.INSTANT]: '立减券',
  [COUPON_TYPES.NEWUSER]: '新人券',
  [COUPON_TYPES.REGULAR]: '普通优惠券',
  [COUPON_TYPES.STACKABLE]: '叠加券'
}

// 优惠券类型颜色映射
export const COUPON_TYPE_COLOR = {
  [COUPON_TYPES.THRESHOLD]: 'primary',
  [COUPON_TYPES.DISCOUNT]: 'success',
  [COUPON_TYPES.INSTANT]: 'warning',
  [COUPON_TYPES.NEWUSER]: 'danger',
  [COUPON_TYPES.REGULAR]: 'info',
  [COUPON_TYPES.STACKABLE]: 'purple'
}

// 优惠券状态枚举
export const COUPON_STATUS = {
  DRAFT: 'draft',              // 草稿
  PENDING: 'pending',          // 待审核
  APPROVED: 'approved',        // 已审核
  REJECTED: 'rejected',        // 已驳回
  ACTIVE: 'active',            // 已上架
  INACTIVE: 'inactive',        // 已下架
  EXPIRED: 'expired',          // 已过期
  EXHAUSTED: 'exhausted'       // 已用完
}

// 优惠券状态文本映射
export const COUPON_STATUS_TEXT = {
  [COUPON_STATUS.DRAFT]: '草稿',
  [COUPON_STATUS.PENDING]: '待审核',
  [COUPON_STATUS.APPROVED]: '已审核',
  [COUPON_STATUS.REJECTED]: '已驳回',
  [COUPON_STATUS.ACTIVE]: '已上架',
  [COUPON_STATUS.INACTIVE]: '已下架',
  [COUPON_STATUS.EXPIRED]: '已过期',
  [COUPON_STATUS.EXHAUSTED]: '已用完'
}

// 优惠券状态颜色映射
export const COUPON_STATUS_COLOR = {
  [COUPON_STATUS.DRAFT]: 'info',
  [COUPON_STATUS.PENDING]: 'warning',
  [COUPON_STATUS.APPROVED]: 'success',
  [COUPON_STATUS.REJECTED]: 'danger',
  [COUPON_STATUS.ACTIVE]: 'success',
  [COUPON_STATUS.INACTIVE]: 'info',
  [COUPON_STATUS.EXPIRED]: 'danger',
  [COUPON_STATUS.EXHAUSTED]: 'warning'
}

// 获取优惠券类型文本
export function getCouponTypeText(type) {
  return COUPON_TYPE_TEXT[type] || '未知类型'
}

// 获取优惠券类型颜色
export function getCouponTypeColor(type) {
  return COUPON_TYPE_COLOR[type] || 'info'
}

// 获取优惠券状态文本
export function getCouponStatusText(status) {
  return COUPON_STATUS_TEXT[status] || '未知状态'
}

// 获取优惠券状态颜色
export function getCouponStatusColor(status) {
  return COUPON_STATUS_COLOR[status] || 'info'
}

// 获取优惠券价值显示文本
export function getCouponValueDisplay(coupon) {
  if (!coupon) return ''
  
  switch (coupon.type) {
    case COUPON_TYPES.THRESHOLD:
      return `满${coupon.minAmount}减${coupon.value}`
    case COUPON_TYPES.DISCOUNT:
      return `${coupon.value}折`
    case COUPON_TYPES.INSTANT:
      return `立减${coupon.value}元`
    case COUPON_TYPES.NEWUSER:
      return `新人专享${coupon.value}元`
    case COUPON_TYPES.REGULAR:
      return `优惠${coupon.value}元`
    case COUPON_TYPES.STACKABLE:
      return `叠加${coupon.value}元`
    default:
      return `${coupon.value}元`
  }
}

// 获取优惠券使用条件显示文本
export function getCouponConditionDisplay(coupon) {
  if (!coupon) return ''
  
  const conditions = []
  
  if (coupon.minAmount > 0) {
    conditions.push(`满${coupon.minAmount}元可用`)
  }
  
  if (coupon.useTime !== 'all') {
    const timeText = {
      day: '仅白天可用',
      night: '仅晚上可用'
    }
    conditions.push(timeText[coupon.useTime])
  }
  
  if (coupon.useScope !== 'all') {
    const scopeText = {
      category: '指定分类可用',
      product: '指定商品可用'
    }
    conditions.push(scopeText[coupon.useScope])
  }
  
  if (coupon.userLevel !== 'all') {
    conditions.push('指定等级可用')
  }
  
  return conditions.length > 0 ? conditions.join('，') : '无限制'
}

// 验证优惠券数据
export function validateCouponData(data) {
  const errors = []
  
  if (!data.name || data.name.trim().length === 0) {
    errors.push('优惠券名称不能为空')
  }
  
  if (!data.type || !Object.values(COUPON_TYPES).includes(data.type)) {
    errors.push('请选择有效的优惠券类型')
  }
  
  if (!data.value || data.value <= 0) {
    errors.push('优惠券价值必须大于0')
  }
  
  if (data.type === COUPON_TYPES.DISCOUNT && (data.value < 0.1 || data.value > 10)) {
    errors.push('折扣率必须在0.1-10之间')
  }
  
  if (!data.total || data.total <= 0) {
    errors.push('发放数量必须大于0')
  }
  
  if (!data.useLimit || data.useLimit <= 0) {
    errors.push('每人限领数量必须大于0')
  }
  
  if (!data.dateRange || data.dateRange.length !== 2) {
    errors.push('请选择有效期')
  }
  
  if (data.dateRange && new Date(data.dateRange[0]) >= new Date(data.dateRange[1])) {
    errors.push('结束时间必须晚于开始时间')
  }
  
  return {
    valid: errors.length === 0,
    errors
  }
}

// 创建优惠券对象
export function createCouponObject(data) {
  return {
    id: data.id || null,
    name: data.name || '',
    type: data.type || COUPON_TYPES.REGULAR,
    value: data.value || 0,
    minAmount: data.minAmount || 0,
    total: data.total || 1,
    used: data.used || 0,
    useLimit: data.useLimit || 1,
    startTime: data.startTime || '',
    endTime: data.endTime || '',
    validDays: data.validDays || 30,
    useTime: data.useTime || 'all',
    useScope: data.useScope || 'all',
    scopeIds: data.scopeIds || [],
    userLevel: data.userLevel || 'all',
    levelIds: data.levelIds || [],
    description: data.description || '',
    status: data.status || COUPON_STATUS.DRAFT,
    createTime: data.createTime || new Date().toISOString(),
    updateTime: data.updateTime || new Date().toISOString()
  }
}
